package com.ruizhong.centercontroll.util;

import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;

public class NetworkAudioPlayer {
    /**@Description: 根据url发送音频
     * @param
     * @return
     * @version v1.0
     * @author fengweijie
     * @date 2024/12/6 15:40
     */
    public static void play(String path){
        Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
        for (Mixer.Info info : mixerInfos) {
            System.out.println("Mixer: " + info.getName() + " - " + info.getDescription());
        }

//        // 选择特定的音频设备（例如第一个设备）
//        Mixer.Info selectedMixerInfo = mixerInfos[0];
//        Mixer selectedMixer = AudioSystem.getMixer(selectedMixerInfo);

        try {
            // 替换为你的网络音频文件的URL
            URL audioURL = new URL(path);
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioURL);
            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);

            Clip audioClip = (Clip) AudioSystem.getLine(info);
            audioClip.open(audioStream);
            audioClip.start();

            // 如果你想让音频播放完毕再继续执行，可以等待Clip结束
            while (!audioClip.isRunning()) Thread.sleep(10);
            while (audioClip.isRunning()) Thread.sleep(100);

            audioClip.close();
            audioStream.close();
        } catch (UnsupportedAudioFileException | LineUnavailableException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
